package core

import (
	"strings"

	"gitee.com/minph/siphan/diycode"
	"gitee.com/minph/siphan/exception"
)

func DecryptFromSlice(val string, codeSlice CodeSlice) (string, error) {
	var res string
	textArr := strings.Split(val, "")

	for i, char := range textArr {
		target, err := codeSlice.FindChar(char)

		if err != nil {
			return "", exception.ErrCharNotFound{Char: char}
		}

		index := target.Index - i

		for len(codeSlice)+1 <= index || index <= -1 {
			if index <= i {
				index = index + len(codeSlice)
			}

			if index >= len(codeSlice)+1 {
				index = index - len(codeSlice)
			}
		}

		if target, err := codeSlice.FindIndex(index); err == nil {
			res += target.Char
		} else {
			return "", exception.ErrIndexNotFound{Index: index}
		}
	}

	if str, err := diycode.DecodeTextByUnicode(res); err != nil {
		return "", err
	} else {
		return str, nil
	}

}

// 解密
// val 密文 key 密钥
func Decrypt(val string, key string) (string, error) {
	keySlice := diycode.GetCodeSliceFromStr(key)
	return DecryptFromSlice(val, keySlice)
}

// 从加密结果直接解密
func DecryptFromResult(encryptResult *EncryptResult) (string, error) {
	return Decrypt(encryptResult.Val, encryptResult.Key)
}
